import django.contrib.auth
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.shortcuts import render, redirect


def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        user = authenticate(username=username, password=password)

        if user is not None:
            django.contrib.auth.login(request, user)
            return redirect("/backend/manage")
        else:
            return render(request, "login.html", {'error': 'Invalid username or password'})


def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        if User.objects.filter(username=username).exists():
            messages.error(request, "Duplicate username")
            return redirect("/backend/register")

        user = User.objects.create_user(username=username, password=password)
        user.save()

        messages.success(request, "Your account has been created!")

        return redirect("/backend/login")


def manage(request):
    return render(request, 'manage.html')
